package com.mindbook.vip.gawxchatinfo.utils.wx;

import com.alibaba.fastjson.JSONObject;
import com.mindbook.vip.gawxchatinfo.exception.AuthCode2SessionException;
import com.mindbook.vip.gawxchatinfo.utils.http.HttpRequestUtils;
import com.mindbook.vip.gawxchatinfo.utils.properties.ApplicationContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @NAME: wxb
 * @DATE: 2022/3/9
 * @Description 微信工具类
 **/
@Component
public class WxUtils {

    //微信登录凭证校验访问地址
    private static final String AUTH_CODE_2_SESSION = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired private HttpRequestUtils httpRequestUtils;

    /**
     * 微信登录凭证校验
     * @param code 微信登录获取到的code值
     * @return 微信登录校验获取到的返回值的对象，然后转成了jsonObject对象
     * 示例：{"session_key":"XxOfPZHtbBfdjMOLzvVF9Q==","expires_in":7200,"openid":"oCKgC0VryWtYbEhzU0c0lwmPTyq4"}
     */
    public JSONObject authCode2Session(String code){
        //构建请求的参数集合
        Map<String,String> map = new LinkedHashMap<>();
        map.put("appid", ApplicationContextUtil.getProperty("wx.wxchat.appid"));
        map.put("secret", ApplicationContextUtil.getProperty("wx.wxchat.appsecret"));
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //发送请求
        String result = httpRequestUtils.sendGetRequest(AUTH_CODE_2_SESSION, map);
        //解析发送请求返回的值
        System.out.println("authCode2SessionResult:"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //根据返回的数据结构，判断当前请求是否成功.判断标准为：返回结果中是否存在session_key值
        if(jsonObject.get("session_key")==""){
            //添加统一返回异常的处理
            throw new AuthCode2SessionException(jsonObject.get("errcode").toString(),jsonObject.get("errmsg").toString());
        }
        return jsonObject;
    }

    /**
     * 获取用户的openId
     * @param code 微信统一发送的code
     * @return
     */
    public String getOpenId(String code){
        JSONObject jsonObject = authCode2Session(code);
        String openid = (String) jsonObject.get("openid");
        return openid;
    }

}
